import React, { Component } from 'react';
import { View, Text, StyleSheet, ScrollView, Image, Platform, AlertIOS, Dimensions } from 'react-native';
import { List, Button, Modal, DatePicker, Toast, Picker } from 'antd-mobile-rn';
import Utils from '../../utils';
import { NavigationActions, StackActions } from 'react-navigation';
import moment from 'moment';
import ImagePicker from 'react-native-image-picker'; //第三方相机
import ImageCropPicker from 'react-native-image-crop-picker'
import userService from '../../service/userService';
import pickerPopup from '../../components/pickerPopup';
import cityPickerPopup from '../../components/cityPickerPopup';
import { BoxShadow } from 'react-native-shadow';
const screen = Dimensions.get("screen");
var photoOptions = {
    //底部弹出框选项
    title: '请选择',
    cancelButtonTitle: '取消',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '选择相册',
    quality: 0.75,
    allowsEditing: true,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
}

const Item = List.Item;

export default class UserDetail extends Component {


    state = {
        birth: new Date(),
        user: {}
    }


    _updateStorage = (user) => {
        const { navigation } = this.props;
        Utils.setStorage("LoginUserInfo", user).then(() => {
            this.setState({
                user: user
            });
            const back = navigation.getParam("back");
            if (back) {
                back(user);
            }
        }).catch((e) => {
            //Toast.info("e:"+e);

        })
    }

    constructor(props) {
        super(props)
        this.navigation = this.props.navigation;

    }

    componentDidMount() {
        console.log("sss:", this.navigation);
        this.setState({
            user: this.navigation.getParam("user", {})
        })

    }


    _updateUser = (key, value, user) => {
        const form = {
            [key]: value
        };


        userService.update(form).then(data => {
            if (data.success) {
                const u = data.result;

                user[key] = u[key];
                this._updateStorage(user);


            }
        })
    }



    render() {

        console.log("ussser::", this.state);

        const { getParam, state, setParams } = this.navigation;

        const user = this.state.user;

        const birth = user.birth ? new Date(user.birth) : this.state.birth;

        const Headimage = (
            <Image source={{ uri: user.image }} style={{ width: 50, height: 50, borderRadius: 25 }} />
        );

        const genders = {
            "0": "未知",
            "1": "男",
            "2": "女",
        }

        return (

            <View style={{ flex: 1, backgroundColor: "#f5f5f9" }}>

                <View style={{ padding: 15 }}>


                    <BoxShadow setting={{
                        width: (screen.width - 30), //包裹的子内容多宽这里必须多宽
                        height: 495,//同上
                        border: 15,//阴影宽度
                        radius: 15,//包裹的子元素圆角多少这里必须是多少
                        opacity: 0.2,//透明度
                        x: 0,
                        y: 8,
                    }}>

                        <View style={{ height: 500, backgroundColor: "#fff", borderRadius: 10, overflow: "hidden" }} >
                            <ScrollView
                                style={{ flex: 1, backgroundColor: '#fff' }}

                            >

                                <List>
                                    <Item arrow="horizontal" extra={Headimage} onClick={() => {
                                        ImagePicker.showImagePicker(photoOptions, (response) => {
                                            console.log('Response = ', response);

                                            if (response.didCancel) {
                                                console.log('User cancelled image picker');
                                            }
                                            else if (response.error) {
                                                console.log('ImagePicker Error: ', response.error);
                                            }
                                            else if (response.customButton) {
                                                console.log('User tapped custom button: ', response.customButton);
                                            }
                                            else {
                                                let source = { uri: response.uri };

                                                // You can also display the image using data:
                                                // let source = { uri: 'data:image/jpeg;base64,' + response.data };
                                                if (Platform.OS === 'ios') {

                                                    this._updateUser("image", response.data, user);

                                                    return;
                                                }

                                                ImageCropPicker.openCropper({
                                                    path: response.uri,
                                                    width: 200,
                                                    height: 200,
                                                    includeBase64: true
                                                }).then(res => {
                                                    console.log('res = ', res);
                                                    this._updateUser("image", res.data, user);
                                                })

                                            }
                                        });
                                    }}>
                                        头像
                        </Item>
                                    <Item arrow="horizontal" extra={user.name} onClick={() => {
                                        if(Platform.OS === "ios"){

                                            AlertIOS.prompt("修改昵称","请输入昵称",[
                                                {text:"取消"},
                                                {text:"确定",onPress:(value)=>{
                                                    if (value) {
                                                        this._updateUser("name", value, user);
                                                    }
                                                }}
                                            ],"plain-text",user.name);
                                            return;
                                        }
                                        Modal.prompt("昵称", "修改昵称", (value) => {
                                            console.log("ni：", value);
                                            if (value) {
                                                this._updateUser("name", value, user);
                                            }

                                        },"default",user.name)
                                    }}>
                                        昵称
                        </Item>
                                    <Item arrow="horizontal" extra={genders[user.gender]} onClick={() => {
                                        pickerPopup("性别", [{
                                            name: "学历",
                                            data: ["未知", "男", "女",].map((value, index) => { return { label: value, value: index } })
                                        }]).then(data => {
                                            console.log("data:", data);
                                            this._updateUser("gender", data[0], user);
                                        })
                                    }}>
                                        性别
                        </Item>
                                    <DatePicker
                                        format={"YYYY-MM-DD"}
                                        mode="date"
                                        minDate={new Date(1920, 1, 1)}
                                        maxDate={new Date()}
                                        value={birth}
                                        extra={user.birth ? (moment(user.birth).format("YYYY-MM-DD")) : ""}
                                        onOk={(value) => {
                                            //console.log("date:val",moment(value).format("YYYY-MM-DD"));
                                            this._updateUser("birth", value.getTime(), user);
                                        }}
                                        onChange={date => {
                                            //user.birth = date.getTime();
                                            this.setState({
                                                birth: date
                                            })

                                        }}
                                    >

                                        <Item arrow="horizontal">
                                            生日
                        </Item>
                                    </DatePicker>

                                    <Item arrow="horizontal" extra={user.address} onClick={() => {
                                        cityPickerPopup("城市").then(value => {
                                            this._updateUser("address", value, user);
                                        })
                                        // let time = new Date().getTime();
                                        // user["name"] = time;
                                        // this.navigation.state.params.user = user;
                                        // Toast.info(JSON.stringify(this.navigation.state.params.user),5);
                                        //setParams("user",Object.assign({name:time},user));
                                    }}>
                                        所在城市
                        </Item>

                                    <Item arrow="horizontal" extra={user.school} onClick={() => {
                                        if (Platform.OS === 'ios') {
                                            AlertIOS.prompt("学校", "修改学校", [
                                                { text: "取消" },
                                                {
                                                    text: "确定", onPress: (value) => {
                                                        if (value) {
                                                            this._updateUser("school", value, user);
                                                        }
                                                    }
                                                }
                                            ],"plain-text",user.school);
                                            return;
                                        }

                                        Modal.prompt("学校", "修改学校", (value) => {
                                            console.log("ni：", value);
                                            if (value) {
                                                this._updateUser("school", value, user);
                                            }

                                        },"default",user.school)
                                    }}>
                                        学校
                        </Item>

                                    <Item arrow="horizontal" extra={user.degree} onClick={() => {
                                        pickerPopup("学历", [{
                                            name: "学历",
                                            data: ["小学", "初中", "中专/高中", "大专", "本科", "硕士", "博士"].map(value => { return { label: value, value: value } })
                                        }]).then(data => {
                                            console.log("data:", data);
                                            this._updateUser("degree", data[0], user);
                                        })
                                    }}>
                                        学历
                        </Item>


                                    <Item arrow="horizontal" extra={user.job} onClick={() => {
                                        pickerPopup("职业", [{
                                            name: "职业",
                                            data: ["学生", "上班族", "自由职业者"].map(value => { return { label: value, value: value } })
                                        }]).then(data => {
                                            console.log("data:", data);
                                            this._updateUser("job", data[0], user);
                                        })

                                    }}>
                                        职业
                        </Item>

                                </List>


                            </ScrollView>
                        </View>
                    </BoxShadow>

                </View>
            </View>
        )

    }
}